/* monitor.c */

#include "monitor.h"

volatile uint32_t monitor_power_volt_adc_val = 0u;
uint32_t monitor_power_volt_adc_val_pre = 0u;

#define APP_MONITOR_POWER_VOLT_ADC_LOW_LIMIT   2979u  /* 3.6v x2. */

void monitor_init(void)
{
    /* perpare the adc task to monitor the power voltage. */
    ADC_ConvInit_Type adc_conv_init;
    adc_conv_init.Resolution = ADC_Resolution_12b;
    adc_conv_init.ConvClkDiv = 2u;
    adc_conv_init.ConvStartupClkCount = 8u;
    adc_conv_init.ConvSamplingClkCount = 8u;
    adc_conv_init.EnableAutoOffMode = false;
    adc_conv_init.EnableWaitMode = true; /* the new conversion would not start if the fifo is full. */
    adc_conv_init.FifoWatermark = 4u;
    adc_conv_init.EnableDma = false;
    adc_conv_init.FifoOverrunMode = ADC_FifoOverrunMode_KeepNewData;
    ADC_InitConv(ADC0, &adc_conv_init);

    /* setup the adc sequence. */
    ADC_ConvSeqConf_Type adc_seq_init;
    adc_seq_init.SeqLen = 1u;
    adc_seq_init.TriggerMode = ADC_TriggerMode_Software;
    adc_seq_init.SeqScanMode = ADC_SeqScanMode_SingleSeq;
    ADC_SetConvSeqConf(ADC0, &adc_seq_init);
    ADC_SetConvSeqSlot(ADC0, 0u, 3u); /* adc0_se3. */
    
    /* power up the adc converter. */
    ADC_RequestConvCmd(ADC0, ADC_ConvCmd_Enable);
    ADC_WaitConvCmd(ADC0, ADC_ConvCmd_Enable);
    
    /* do software trigger the converter. */
    ADC_RequestConvCmd(ADC0, ADC_ConvCmd_Start);


    /* setup the systick. */
    SysTick_Config(CLOCK_SYSTICK_FREQ_HZ / 10u); /* 100hz. */
}

void SysTick_Handler(void)
{
    uint32_t adc_channel_index = 0u;
    
    ADC_GetConvValue(ADC_GetFifoDataRaw(ADC0), &adc_channel_index, (uint32_t *)&monitor_power_volt_adc_val);
    
    if (   (monitor_power_volt_adc_val <= APP_MONITOR_POWER_VOLT_ADC_LOW_LIMIT)
        && (monitor_power_volt_adc_val_pre > APP_MONITOR_POWER_VOLT_ADC_LOW_LIMIT) )
    {
        buzzer_on();
    }
    
    if (   (monitor_power_volt_adc_val >= APP_MONITOR_POWER_VOLT_ADC_LOW_LIMIT)
        && (monitor_power_volt_adc_val_pre < APP_MONITOR_POWER_VOLT_ADC_LOW_LIMIT) )
    {
        buzzer_off();
    }
    
    monitor_power_volt_adc_val_pre = monitor_power_volt_adc_val;
    
    ADC_RequestConvCmd(ADC0, ADC_ConvCmd_Start);
}


/* EOF. */

